package cn.lwj.controller;

import cn.lwj.common.BaseContext;
import cn.lwj.common.R;
import cn.lwj.dto.SetmealDto;
import cn.lwj.pojo.Category;
import cn.lwj.pojo.Employee;
import cn.lwj.pojo.Setmeal;
import cn.lwj.pojo.SetmealDish;
import cn.lwj.service.CategoryService;
import cn.lwj.service.SetmealDishService;
import cn.lwj.service.SetmealService;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetMealController {

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    SetmealService setmealService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    SetmealDishService setmealDishService;

    /**
     * 套餐管理分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
//    @Cacheable(value = "setmeal",key = "#page + #pageSize + (#name == null ? '' : #name)",unless = "#result == null")
    public R<Page> page(Integer page,Integer pageSize,String name){

//        1.创建分页构造器
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>();
//        2.条件查询
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
//        如果是模糊查询 则需要条件like 条件
        lqw.like(name != null,Setmeal::getName,name);
        lqw.orderByDesc(Setmeal::getUpdateTime);
//        3.分页查询
        setmealService.page(pageInfo,lqw); // 查询之后参数会自动封装至pageInfo当中
//        4.pageInfo对象的records属性没有分类名称 所以需要单独处理
        List<Setmeal> setmeals = pageInfo.getRecords();
//        将除了records属性的其余属性复制至setmealDtoPage当中 给前端返回
        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");
        List<SetmealDto> setmealDtos = setmeals.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
//            先将item的属性拷贝给setmealDto在设置categoryName的值
            BeanUtils.copyProperties(item, setmealDto);
            Category category = categoryService.getById(item.getCategoryId());
            setmealDto.setCategoryName(category.getName());
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(setmealDtos);
        return R.success(setmealDtoPage);
    }


    /**
     * 新增套餐和套餐对应的菜品
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmeal",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info(setmealDto.toString());
        setmealService.saveSetmealWithDish(setmealDto);
        return R.success("添加成功");
    }


    /**
     * 通过套餐id回显套餐和对应菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getSetmealById(@PathVariable long id){
        System.out.println( "id = " + id);
        Setmeal setmeal = setmealService.getById(id);
        if(setmeal == null){
            R.error("套餐不存在");
        }
//        由于修改的不只是套餐 还有套餐所对应的菜品 所以需要封装为一个dto进行返回
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto); // 拷贝Setmeal的属性
//        通过套餐id查询套餐对应的菜品
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> SetmealDishList = setmealDishService.list(lqw);
        setmealDto.setSetmealDishes(SetmealDishList);
        System.out.println("**********************");
        System.out.println(setmealDto);
        if(SetmealDishList.size()<=0) {
            return R.error("套餐菜品发生错误");
        }
        return R.success(setmealDto);
    }


    /**
     * 修改套餐
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmeal",allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto){
        setmealService.updateSetmealWithDish(setmealDto);
        return R.success("套餐更新成功");
    }


    /**
     * 修改状态
     * @param statusCode
     * @param ids
     * @return
     */
    @PostMapping("/status/{statusCode}")
    public R<String> updateStatus(@PathVariable int statusCode, String ids){
        setmealService.updateStatus(statusCode,ids);
        return R.success("修改成功");
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
//    @DeleteMapping
//    public R<String> delete(String ids){
//        setmealService.deleteSetmeal(ids);
//        return R.success("删除成功");
//    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmeal",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids){
        setmealService.delete(ids);
        return R.success("删除成功");
    }


    /**
     *
     * @param setmeal
     * @return
     */
    @Cacheable(value = "setmeal",key = " 'setmeal_' + #setmeal.categoryId + '_' + #setmeal.status ",unless = "#result == null")
    @GetMapping("/list")
    public R<List<SetmealDto>> list(Setmeal setmeal){
        System.out.println(setmeal.toString());
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Setmeal::getCategoryId,setmeal.getCategoryId());
        lqw.eq(Setmeal::getStatus,1);
        List<Setmeal> list = setmealService.list(lqw);
        List<SetmealDto> setmealDtoList = list.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            return setmealDto;
        }).collect(Collectors.toList());
        return  R.success(setmealDtoList);
    }

}
